package service

import (
	"context"

	"gitee.com/WisdomClassroom/core/protobufs/v1/pb"
	"gitee.com/WisdomClassroom/knowledgePoint/glb"
)

func (s Service) ListCourseKnowledgePoints(ctx context.Context, request *pb.ListCourseKnowledgePointsRequest) (*pb.ListCourseKnowledgePointsResponse, error) {
	rows, err := glb.DB.Raw(
		`select knowledge_point.uuid, knowledge_point.name, knowledge_point.chapter_uuid from course_model
			join chapter_model on chapter_model.course_uuid = course_model.uuid
			join knowledge_point on knowledge_point.chapter_uuid = chapter_model.uuid
			where course_model.uuid = ?`, request.GetCourseUUID(),
	).Rows()
	defer func() {
		errDefer := rows.Close()
		if errDefer != nil {
			glb.Logger.Error(errDefer.Error())
		}
	}()
	if err != nil {
		glb.Logger.Error(err.Error())
		return listCourseKnowledgePointRespSvrErr, nil
	}

	knowledgePointsResp := make([]*pb.KnowledgePointFullInfo, 0, 32)
	for rows.Next() {
		knowledgePoint := &pb.KnowledgePointFullInfo{}
		err := rows.Scan(&knowledgePoint.UUID, &knowledgePoint.Name, &knowledgePoint.ChapterUUID)
		if err != nil {
			glb.Logger.Error(err.Error())
			return listCourseKnowledgePointRespSvrErr, nil
		}
		knowledgePointsResp = append(knowledgePointsResp, knowledgePoint)
	}

	return &pb.ListCourseKnowledgePointsResponse{
		Status:          &pb.ResponseStatus{Code: pb.ResponseStatusCode_Success},
		KnowledgePoints: knowledgePointsResp,
	}, nil
}
